package com.example.bankingsystemandroid;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;

import com.example.bankingsystemandroid.Holder.InfoHolder;
import com.example.bankingsystemandroid.utils.PropertiesConfig;
import com.example.bankingsystemandroid.utils.PropertyManager;

public class SplashScreenActivity extends Activity {
	private Context context;
	// Splash screen timer
//	private static int SPLASH_TIME_OUT = 5000;
//	private ProgressBar pro;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		try {
			InitialConfig(context);
		} catch (IOException e1) {
			// Quit Application
			e1.printStackTrace();
		}
		setContentView(R.layout.splash_screen);
		context = this;
		try {
			InitialConfig(context);
		} catch (IOException e1) {
			// Quit Application
			e1.printStackTrace();
		}
		if (gotToken()) {
			validateToken();
		} else {
			Intent intent = new Intent(getApplicationContext(),
					LoginActivity.class);
			startActivity(intent);
			finish();
		}
	}

	private boolean gotToken() {
		SharedPreferences pre = getSharedPreferences(InfoHolder.PREFS_NAME,
				MODE_PRIVATE);
		boolean result;
		String token = pre.getString("token", "");
		if ("".equals(token)) {
			result = false;
			Log.i("check token", "no token");
		} else {
			result = true;
			InfoHolder.setToken(token);
			String username = pre.getString("username", "");
			InfoHolder.setUsername(username);
			Log.i("check token", "have token");
		}
		return result;

	}

	private void validateToken() {
		ValidateTokenTask validateTokenTask = new ValidateTokenTask(
				getApplicationContext());
		String token = InfoHolder.getToken() + "@" + InfoHolder.getUsername();

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("token", token));

		validateTokenTask.execute(postParameters);
	}
	
	public void InitialConfig(Context context) throws IOException {
		PropertiesConfig propertiesConfig = new PropertiesConfig(context);
	}

	private class ValidateTokenTask extends
			AsyncTask<ArrayList<NameValuePair>, Void, Void> {
		Context context;

		public ValidateTokenTask(Context context) {
			super();
			this.context = context.getApplicationContext();
		}

		@Override
		protected void onPostExecute(Void result) {
			if (!"".equals(InfoHolder.getToken())) {
				context.startActivity(new Intent(context, MainActivity.class)
						.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
				finish();
			} else {
				context.startActivity(new Intent(context, LoginActivity.class)
						.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
				finish();
			}
			super.onPostExecute(result);
		}
		
		

		@Override
		protected Void doInBackground(ArrayList<NameValuePair>... params) {
//			if (isURLReachable(getApplicationContext())) {
//				
//			} else {
//				//server not response
//				new AlertDialog.Builder(SplashScreenActivity.this)
//				.setMessage("Server is not response, please try again later!")
//				.setCancelable(false)
//				.setPositiveButton("Exit",
//						new DialogInterface.OnClickListener() {
//							public void onClick(DialogInterface dialog,
//									int id) {
//								finish();
//							}
//						}).show();
//			}
			
			/*
			 * Create the POST request
			 */
			HttpClient httpClient = new DefaultHttpClient();
			String serverIP = PropertiesConfig
					.getProperty(PropertyManager.SERVER_IP);
			String serverPort = PropertiesConfig
					.getProperty(PropertyManager.SERVER_PORT);
			HttpPost httpPost = new HttpPost(
					"http://" + serverIP + ":"
					+ serverPort + "/bankingsystem/j_spring_security_check");
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params[0]));
			} catch (UnsupportedEncodingException e2) {
				e2.printStackTrace();
			}

			/*
			 * Execute the HTTP Request
			 */
			try {
				httpPost.addHeader("Cookie",
						"JSESSIONID=" + InfoHolder.getSessionId());

				HttpResponse response = httpClient.execute(httpPost);
				HttpEntity respEntity = response.getEntity();

				if (respEntity != null) {
					String retSrc = EntityUtils.toString(respEntity);
					JSONObject result = new JSONObject(retSrc);
					String errorCode = result.getString("errorCode");
					if ("TOKEN_EXPIRED".equals(errorCode)
							|| "INVALID_TOKEN".equals(errorCode)
							|| "ALGORITHM_NOT_SUPPORT".equals(errorCode)
							|| "TOKEN_NOT_FOUND".equals(errorCode)) {
						// request sign in
						Log.i("validate token", "token expired");
						InfoHolder.clearInfo();
					} else {
						String token = result.getString("token");
						if (token != null) {
							Log.i("validate token", "token not expired");
							Header[] headers = response.getAllHeaders();
							for (Header header : headers) {
								if ("Set-Cookie".equals(header.getName())) {
									String headerValue = header.getValue();
									InfoHolder
											.setSessionId(headerValue.substring(
													headerValue.indexOf("=") + 1,
													headerValue.indexOf(";")));
									Log.i("HeaderName", "Header name: "
											+ header.getName());
									Log.i("HeaderValue", "Header value: "
											+ header.getValue());
								}
							}
						}
					}
				}
			} catch (ClientProtocolException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (IOException e) {
				// writing exception to log
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}
	
	static public boolean isURLReachable(Context context) {
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    String serverIP = PropertiesConfig
				.getProperty(PropertyManager.SERVER_IP);
	    String serverPort = PropertiesConfig
				.getProperty(PropertyManager.SERVER_PORT);
	    if (netInfo != null && netInfo.isConnected()) {
	        try {
	            URL url = new URL("http://" + serverIP + ":"
						+ serverPort + "/bankingsystem");   // Change to "http://google.com" for www  test.
	            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
	            urlc.setConnectTimeout(10 * 1000);          // 10 s.
	            urlc.connect();
	            if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
	                Log.wtf("Connection", "Success !");
	                return true;
	            } else {	            	
	                return false;
	            }
	        } catch (MalformedURLException e1) {
	            return false;
	        } catch (IOException e) {
	            return false;
	        }
	    }
	    return false;
	}
}
